package com.liuyucheng.idea_springboot.aspect;


import com.liuyucheng.annotation.NotAllowRepeat;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 防止重复提交
 */
@Slf4j
@Aspect
@Component
public class AvoidRepeatSubmitAspect {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 定义一个切点
     */
    @Pointcut(value = "@annotation(com.liuyucheng.annotation.NotAllowRepeat)")
    public void access() {}

    /**
     * 前置通知
     * @param point 切点
     */
    @Before("access()")
    public void before(JoinPoint point) {
    }


    /**
     * 后置通知,不管方法执行成功还是失败,都会进入这里
     * @param point 切点
     */
    @After("access()")
    public void after(JoinPoint point) {
    }

    /**
     * 正常执行完成后进入
     * @param point 切点
     */
    @AfterReturning("access()")
    public void afterReturning(JoinPoint point) {
    }

    /**
     * 执行出现异常后进入
     * @param point 切点
     */
    @AfterThrowing("access()")
    public void afterThrowing(JoinPoint point) {
        //释放锁
    }

    /**
     * 环绕通知,是在before前就会触发
     * @param point 切点
     * @return 执行结果
     * @throws Throwable 异常
     */
    @Around("access()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        log.info("{}",redisTemplate);
        //执行前
        NotAllowRepeat annotation = ((MethodSignature) point.getSignature()).getMethod().getAnnotation(NotAllowRepeat.class);
        //锁的类型
        String type = annotation.type();
        //方法传参
        Object[] args = point.getArgs();

        if(NotAllowRepeat.ELEMENT_VALIDATE.equals(type)){
            log.info("六要素进件");
        }else if(NotAllowRepeat.SUBMIT.equals(type)){
            log.info("提交");
            for(Object obj : args){
                if(obj instanceof Map){
                    Map map = (Map)obj;
                    map.get("");
                }
            }
        }

        //执行方法
        Object result = point.proceed();

        //执行后
        //释放锁
        log.info("释放锁");

        return result;
    }

}